package fr.sportsurbains;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.android.gcm.GCMRegistrar;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import fr.sportsurbains.reader.TopicsReader;
import fr.sportsurbains.tools.BitmapManager;
import fr.sportsurbains.tools.DBManager;

@SuppressLint("HandlerLeak")
public class MainActivity extends FragmentActivity implements
		ActionBar.TabListener {


	
	MyPagerAdapter mPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;
	BitmapManager bmpManager;
	ProgressDialog progressDialog;
	Handler refreshHandler;
	Handler initHandler;
	Handler loadHandler;
	DBManager dbmanager;
	AsyncTask<Void, Void, Void> mRegisterTask;
	List<List<Map<String,String>>> categories;
	List<BaseAdapter> adapters;
	List<ListView> listviews;
	List<View> views;
	SharedPreferences settings;
	
	TopicsReader tr;
	ListView lv;
	ViewBinder vb = new ViewBinder() {

		@Override
		public boolean setViewValue(  
                View view,   
                Object data,    
             String textRepresentation) {    
	        if(view instanceof ImageView  && data instanceof String){ 
	            ImageView iv = (ImageView) view;    
	            bmpManager.loadBitmap((String)data, iv);
	            return true;    
	        }else if(view.getId() == R.id.topic) {
	        	view.setTag(data);
	        	return true;
	        }else    return false;    
		}
	};

	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		settings = PreferenceManager.getDefaultSharedPreferences(this);
		String notif_key = getString(R.string.notif_key);
		boolean notif_enabled = settings.getBoolean(notif_key, false);
		if(notif_enabled) {
			enableNotification();
		}
		
        
		dbmanager = new DBManager(this);
		bmpManager = new BitmapManager(BitmapFactory.decodeResource(getResources(), R.drawable.loading17), dbmanager);

		progressDialog = new ProgressDialog(MainActivity.this);
		progressDialog.setTitle(getResources().getString(R.string.progressdialog_title));
		progressDialog.setMessage(getResources().getString(R.string.progressdialog_message));
		refreshHandler = new Handler() {
			@Override
			public void handleMessage (Message msg) {
				switch(msg.what) {
				case 0: progressDialog.show();break;
				case 1: progressDialog.hide();
					int section_position = mViewPager.getCurrentItem();
					
					refreshListView(section_position,false);
					break;
				}					
			}
		};
		
		loadHandler = new Handler() {
			@SuppressLint("HandlerLeak")
			@Override
			public void handleMessage (Message msg) {
				switch(msg.what) {
				case 0: progressDialog.show();break;
				case 1: progressDialog.hide();
					int section_position = mViewPager.getCurrentItem();
					
					refreshListView(section_position,true);
					break;
				}					
			}
		};
		
		initHandler = new Handler() {
			@Override
			public void handleMessage (Message msg) {
				for(int i = 0;i < 3; i++) {
					SimpleAdapter adp = new SimpleAdapter(views.get(i).getContext(),categories.get(i),R.layout.topic,new String[]{"link","title","image","summary"},
							new int[]{R.id.topic,R.id.topic_title,R.id.topic_picture,R.id.topic_summary});
					adp.setViewBinder(vb);
					int id = 0;
					switch(i) {
					case 0: id = R.id.section_news;break;
					case 1: id = R.id.section_revuedepresse;break;
					case 2: id = R.id.section_videos;break;
					}
					ListView listview = (ListView) views.get(i).findViewById(id);
					listview.setAdapter(adp);
					listview.setOnItemClickListener(new MyOnItemClickListener());
					listview.setOnScrollListener(new MyOnScrollListener());
					adapters.add(adp);
				}
				
			}
		};

		// Set up the action bar.
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.

		View viewPagerNews1 = LayoutInflater.from(this).inflate(R.layout.fragment_main_news, null);
		View viewPagerNews2 = LayoutInflater.from(this).inflate(R.layout.fragment_main_revuedepresse, null);
		View viewPagerNews3 = LayoutInflater.from(this).inflate(R.layout.fragment_main_videos, null);
		View viewPagerNews4 = LayoutInflater.from(this).inflate(R.layout.fragment_main_reporter, null);
		views = new ArrayList<View>();
		views.add(viewPagerNews1);
		views.add(viewPagerNews2);
		views.add(viewPagerNews3);
		views.add(viewPagerNews4);
		mPagerAdapter = new MyPagerAdapter(this,views);

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mPagerAdapter);

		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
					}
				});
		
		categories = new ArrayList<List<Map<String,String>>>();
		adapters = new ArrayList<BaseAdapter>();

		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			actionBar.addTab(actionBar.newTab()
					.setText(mPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}
		new Thread() {
			@Override
			public void run() {
				initListView(16);
				initHandler.sendEmptyMessage(0);
			}
		}.start();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.dbmanager.closeDB();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.action_refresh:
			new Thread() {
				@Override
				public void run() {
					refreshHandler.sendEmptyMessage(0);
						try {
							tr = new TopicsReader(getHomePage());
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					refreshHandler.sendEmptyMessage(1);
				}
			}.start();break;
		case R.id.action_recommend_to_friend:
			Uri smsToUri = Uri.parse("smsto:");    
			Intent mIntent = new Intent( android.content.Intent.ACTION_SENDTO, smsToUri );  
			mIntent.putExtra("sms_body", getResources().getString(R.string.action_content_invite));  
			startActivity( mIntent );   
			break;
		case R.id.action_about:
			Intent aint = new Intent(MainActivity.this,AboutActivity.class);
			startActivity(aint);
			break;
		case R.id.action_search:
			Intent sint = new Intent(MainActivity.this,SearchActivity.class);
			startActivity(sint);
			break;
		case R.id.action_settings:
			Intent setint = new Intent(MainActivity.this,SettingsActivity.class);
			startActivityForResult(setint,0);
		}
		return false;
		
	}
	
	protected  void onActivityResult(int requestCode, int resultCode, Intent data) {  
		String notif_key = getString(R.string.notif_key);
		boolean notif_enabled = settings.getBoolean(notif_key, false);
		if(notif_enabled) {
			enableNotification();
		} else {
			disableNotification();
		}
    }  

	@Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
			mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}
	
	public void initListView(int count) {
		for(int i = 0; i < 3; i++) {
			String category = null;
			switch(i) {
			case 0: category = "news";break;
			case 1: category = "revue_de_presse";break;
			case 2: category = "videos";break;
			}
			List<Map<String,String>> topics = new ArrayList<Map<String,String>>();
			topics.addAll(dbmanager.getTopicsByCategory(category,count));
			categories.add(topics);
		}
	}
	
	public void refreshListView(final int tabid, boolean option) {
		int id = 0;
		String table = null;
		switch(tabid) {
		case 0: id = R.id.section_news;table = "news";break;
		case 1: id = R.id.section_revuedepresse;table = "revue_de_presse";break;
		case 2: id = R.id.section_videos;table = "videos";break;
		}
		List<Map<String,String>> topics = tr.getTopics();
		dbmanager.addTopics(topics, table);
		if(option == false) {
			List<Map<String,String>> category = categories.get(tabid);
			category.clear();
			category.addAll(topics);
			ListView listview = (ListView) views.get(tabid).findViewById(id);
			listview.setTag(tr.getNextUrl());
			adapters.get(tabid).notifyDataSetChanged();
		} else {
			List<Map<String,String>> category = categories.get(tabid);
			category.addAll(topics);
			ListView listview = (ListView) views.get(tabid).findViewById(id);
			listview.setTag(tr.getNextUrl());
			adapters.get(tabid).notifyDataSetChanged();
		}
	}
	
	public void disableNotification() {
		if (GCMRegistrar.isRegisteredOnServer(this)) {
			GCMRegistrar.unregister(this);
		}
	}
	
	public void enableNotification() {
		GCMRegistrar.checkDevice(this);  
        GCMRegistrar.checkManifest(this);  
        final String regId = GCMRegistrar.getRegistrationId(this);  
        if (regId.equals("")) {  
          GCMRegistrar.register(this, GCMIntentService.SENDERID);  
          Log.v("TEST", "new device:"+GCMRegistrar.isRegistered(this)+GCMRegistrar.getRegistrationId(this));  
        } else {  
        	if (GCMRegistrar.isRegisteredOnServer(this)) {
                // Skips registration.
            } else {
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        boolean registered =
                                ServerUtilities.register(context, regId);
                        // At this point all attempts to register with the app
                        // server failed, so we need to unregister the device
                        // from GCM - the app will try to register again when
                        // it is restarted. Note that GCM will send an
                        // unregistered callback upon completion, but
                        // GCMIntentService.onUnregistered() will ignore it.
                        if (!registered) {
                            GCMRegistrar.unregister(context);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }

                };
                mRegisterTask.execute(null, null, null);
            }
          Log.v("TEST", "Already registered:"+GCMRegistrar.getRegistrationId(this));  
        }  
	}
	
	public String getHomePage() {
		int section_position = mViewPager.getCurrentItem();
		String temp = null;
		switch(section_position) {
			case 0:
				temp = "http://www.sportsurbains.fr/category/news/";
				break;
			case 1:
				temp = "http://www.sportsurbains.fr/category/revue-de-presse/";
				break;
			case 2:
				temp = "http://www.sportsurbains.fr/category/videos/";
				break;
			case 3:
				temp = null;
				break;
			default:
		}
		return temp;
	}
	
	public class MyOnScrollListener implements OnScrollListener {
		private boolean isLast = false;


		@Override
		public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount > 0) {      
                isLast = true;   
            }      
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			if (isLast && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {      
                //加载元素      
				final String url = (String)view.getTag();
				if(url != null) {
					new Thread() {
						@Override
						public void run() {
							loadHandler.sendEmptyMessage(0);
								try {
									tr = new TopicsReader(url);
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							loadHandler.sendEmptyMessage(1);
						}
					}.start();
	             
	                isLast = false;      
				}
            }      
		}
		
	}
	
	class MyOnItemClickListener implements ListView.OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			if(arg1.getTag() != null) {
				/*Intent it = getIntent();
				it.setClass(MainActivity.this, WebActivity.class);
				Bundle bd = new Bundle();
				bd.putString("link", (String)arg1.getTag());
				it.putExtras(bd);
				startActivity(it);*/
				Intent tint = new Intent(Intent.ACTION_VIEW,Uri.parse((String)arg1.getTag()));
				startActivity(tint);
			}
			
		}
		
	}
}
